package com.tippix.imagepresizer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.json.JSONException;
import org.json.JSONObject;

import com.palm.luna.LSException;
import com.palm.luna.message.ErrorMessage;
import com.palm.luna.service.LunaServiceThread;
import com.palm.luna.service.ServiceMessage;

public class ImagePREsizerEngine extends LunaServiceThread {

    private String name = "ImagePREsizer";
    private String version = "0.1.0";
 
	@LunaServiceThread.PublicMethod
	public void test(ServiceMessage msg) throws InterruptedException, JSONException, LSException, IOException
	{ 
		try
		{
			boolean result = false;
			
			JSONObject reply = new JSONObject(); 
			reply.put("result", result); 
			msg.respond(reply.toString());

		}
		catch (LSException e) 
		{
			this.logger.severe("", e);
		}
	}
    
	@LunaServiceThread.PublicMethod
	public void resize(ServiceMessage msg) throws InterruptedException, JSONException, LSException, IOException
	{ 
		try
		{
			if (msg.getJSONPayload().has("input") && 
					msg.getJSONPayload().has("output") &&
					msg.getJSONPayload().has("width") &&
					msg.getJSONPayload().has("height")) 
			{
				String inputParam = msg.getJSONPayload().getString("input");
				String outputParam = msg.getJSONPayload().getString("output");
				String widthParam = msg.getJSONPayload().getString("width");
				String heightParam = msg.getJSONPayload().getString("height");
				
				if (isLegalString(inputParam) &&
						isLegalString(outputParam) &&
						isLegalString(widthParam) &&
						isLegalString(heightParam))
				{
					Process p = Runtime.getRuntime().exec(
							"/opt/bin/convert " +
							inputParam +
							" -filter cubic " +
							" -resize "	+
							widthParam +
							"x" +
							heightParam +
							"! " +
							outputParam);
					
					BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
					String line = null; 
					String output = ""; 
					while ((line = input.readLine()) != null) { 
						output = output + line; 
					} 
					input.close();
					JSONObject reply = new JSONObject(); 
					reply.put("output", output); 
					msg.respond(reply.toString());
					p.waitFor();
				}
				else 
				{
					msg.respondError(ErrorMessage.ERROR_CODE_INVALID_PARAMETER, "Invalid value for one of the parameters");
				}
			}
			else 
			{
			    msg.respondError(ErrorMessage.ERROR_CODE_INVALID_PARAMETER, "Missing parameters");
			}
		}
		catch (LSException e) 
		{
			this.logger.severe("", e);
		}
	}
    
	@LunaServiceThread.PublicMethod
	public void identify(ServiceMessage msg) throws InterruptedException, JSONException, LSException, IOException
	{ 
		try
		{
			if (msg.getJSONPayload().has("input")) 
			{
				String inputParam = msg.getJSONPayload().getString("input");
				if (isLegalString(inputParam))
				{
					Process p = Runtime.getRuntime().exec("/opt/bin/identify -format %wx%hx%b " + inputParam); 
					BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
					String line = null; 
					String output = ""; 
					while ((line = input.readLine()) != null) { 
						output = output + line; 
					} 
					input.close();
					String[] splitted = output.split("x");
					JSONObject reply = new JSONObject(); 
					reply.put("width", splitted[0]); 
					reply.put("height", splitted[1]);
					reply.put("size", splitted[2]);
					msg.respond(reply.toString());
					p.waitFor();
				}
				else 
				{
					msg.respondError(ErrorMessage.ERROR_CODE_INVALID_PARAMETER, "Invalid value for 'input' parameter");
				}
			}
			else 
			{
			    msg.respondError(ErrorMessage.ERROR_CODE_INVALID_PARAMETER, "Missing 'input' parameter");
			}
		}
		catch (LSException e) 
		{
			this.logger.severe("", e);
		}
	}
	
	@LunaServiceThread.PublicMethod
	public void version(ServiceMessage msg) throws JSONException, LSException
	{
		try
		{
			JSONObject reply = new JSONObject(); 
			reply.put("name", this.name); 
			reply.put("version", this.version); 
			msg.respond(reply.toString());
		}
		catch (LSException e) 
		{
			this.logger.severe("", e);
		}
	}
	
	@LunaServiceThread.PublicMethod
	public void status(ServiceMessage msg) throws JSONException, LSException
	{
		try
		{
			JSONObject reply = new JSONObject();
			reply.put("returnValue",true);
			msg.respond(reply.toString());
		}
		catch (LSException e) 
		{
			this.logger.severe("", e);
		}
	}

	
	public static boolean isLegalString( String parameter )
	{
		boolean isValid=true;
			String validChars="abcdefghijklmnopqrstuvwxyz0123456789._-/*\"\\";
		parameter=parameter.toLowerCase(); // case desensitize
		for (int i=0;i<parameter.length();i++)
		{
			char c=parameter.charAt(i);
			if (validChars.indexOf(c)== -1)
			{
				isValid=false;
				break;
			}
		}
		return isValid;
	}
	
}
